#include "ODN_GameTimer.h"

#define DEFAULT_TICKS_PER_SEC 20

namespace ouden {

CGameTimer::CGameTimer()
 : m_iTimePerTick(1000/DEFAULT_TICKS_PER_SEC)
{

	//Create an instance of an Ogre timer so we can get the current time accuratly
    m_pOgreTimer = Ogre::PlatformManager::getSingleton().createTimer();
    
    //Initialise the variables to the current time
    m_iCurTime = m_pOgreTimer->getMilliseconds();
    m_iLastFrameTime = m_iCurTime;
    
    m_fTickExcess = 0;
	
}

bool CGameTimer::update(IGameTimerListener* pListener)
{

	//Calculate the new time variables
	
	//Store the current time in a temporary variable
    long iNow = m_pOgreTimer->getMilliseconds();
    
    //Calculate the elapsed time since the last frame
	m_iElapsed = iNow - m_iCurTime;
	
	//Calculate quick values only once per frame
    m_iElapsed2 = m_iElapsed * m_iElapsed;
	
    //Update the timer
    m_iCurTime = iNow;
	
	//Check if a second has passed 
    if(iNow - m_iLastFrameTime >= 1000){
    
    	//Calculate the FPS and reset the counter variables
        m_iFPS 				= m_iFPSCounter + 1;
        m_iFPSCounter 		= 0;
        m_iLastFrameTime 	= iNow;
    
    }
    else{
	
		//Otherwise increase the FPS
        ++m_iFPSCounter;
	
    }
	
	//Calculate the number of ticks that should have passed
	Scalar fNumTicks = (float)m_iElapsed / (float)(m_iTimePerTick) + m_fTickExcess;
	
	//Get the fractional excess to add on next time
	m_fTickExcess = fNumTicks - int(fNumTicks);
	
	//Call onTick the for each whole tick that should have passed
	for (int i=0;i<int(fNumTicks);i++) {
		if ( !pListener->onTick(this) )
			return false;
	}
	
	//Call the frameStarted function once per frame
	return ( pListener->onFrameStart(this) );
	
}

} //namespace ouden
